package com.lovo.atm.dao.impls;

import com.lovo.atm.bean.UserBean;
import com.lovo.atm.dao.IUserDao;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class IUserDaoImpls extends BaseDao implements IUserDao {
    @Override
    public UserBean login(String name, String pwd) {
        UserBean linkObj = new UserBean();
//        链接
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_atms where pk_name=? and l_password=? ");
            ps.setObject(1,name);
            ps.setObject(2,pwd);
//            结果集
            rs = ps.executeQuery();
            while (rs.next()){
                linkObj.setName(rs.getString("pk_name"));
                linkObj.setPwd(rs.getString("l_password"));
                linkObj.setAccount(rs.getDouble("l_money"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//            关闭
            this.closeConnection();
        }
        return linkObj;
    }

    @Override
    public void update(String code, double money) {
        this.setConnection();
        try {

//            执行sql语句
            ps = con.prepareStatement("update t_atms set l_money+=? where pk_name=?");

            ps.setObject(1,money);
            ps.setObject(2,code);

            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//            关闭
            this.closeConnection();

        }

    }

    @Override
    public UserBean findByName(String code) {
        List list = new ArrayList<>();

//        链接
        this.setConnection();
        try {
            ps = con.prepareStatement("select * from t_atms where pk_name=?");
            ps.setObject(1,code);

//            结果集
            rs = ps.executeQuery();
            while (rs.next()){
                UserBean linkObj = new UserBean();
                linkObj.setName(rs.getString("pk_name"));
                linkObj.setPwd(rs.getString("l_password"));
                linkObj.setAccount(rs.getDouble("l_money"));
                list.add(linkObj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
//            关闭
            this.closeConnection();
        }

        return list.size() == 0 ? null : (UserBean) list.get(0);
    }

    public static void main(String[] args) {
        IUserDao dao = new IUserDaoImpls();
        System.out.println(dao.findByName("张3"));
    }
}
